﻿using NoteSystem.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Reflection.Emit;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NoteSystem
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitNote();
            }
        }
        #region  登录用户信息加载
        public string InitUser()
        {
            if (Session["User"] == null)
                return "";
            DataRow userRow = (DataRow)Session["User"];
            int id = Convert.ToInt32(userRow["district_id"]);
            string sql = string.Format("select c.CityName from S_District d inner join S_City c on c.CityID=d.CityID  where DistrictID=" + id);
            DataSet ds = DbHelper.Query(sql);
            string genderText = userRow["gender"].ToString() == "0" ? "男" : "女";
            string cityName = ds.Tables[0].Rows[0]["CityName"].ToString();
            string url = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v61&appid=63151463&appsecret=htDCG9mE&city=" + cityName.Replace("市","");
            WebClient client = new WebClient();//实例化一个远程访问类
            byte[] byteResuit = client.DownloadData(url);//使用访问类 请求接口 并将接口内容解析为字符串
            string result = Encoding.UTF8.GetString(byteResuit);//JSON
            //借用第三方序列化反序列化库Newtonsoft
            JObject obj = (JObject)JsonConvert.DeserializeObject(result);//将json字符串反序列化为一个newtonsoft提供的一个对象
            //取你要的内容
            string wea = obj["wea"].ToString();
            string tem1 = obj["tem1"].ToString();
            string tem2 = obj["tem2"].ToString();
            //登录人信息
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("<div class=\"segment left\">");
            stringBuilder.Append("<i class=\" glyphicon glyphicon-user left\"></i>");
            stringBuilder.Append($"     <h3 class=\"left\">欢迎{userRow["account"]}登录<br>");
            stringBuilder.Append("  <span>管理这个设备及其传感器</span>");
            stringBuilder.Append("  </h3>");
            stringBuilder.Append(" </div>");
            stringBuilder.Append("<div class=\"clear\"></div>");
            stringBuilder.Append("  <div class=\"segment2\">");
            stringBuilder.Append("  <div class=\"user_left\">");
            stringBuilder.Append($"  <img width=\"160\" height=\"160\" src=\"{userRow["img_url"]}\">");
            stringBuilder.Append("  </div>");
            stringBuilder.Append(" <div class=\"user_right\">");
            stringBuilder.Append($"<h5>你好：{userRow["account"]}<br>");
            stringBuilder.Append($" <span><i class=\"glyphicon glyphicon-time\"></i>&nbsp;{DateTime.Now}</span>");
            stringBuilder.Append("    </h5>");
            stringBuilder.Append("<p>");
            stringBuilder.Append($"  所在地:{cityName}<br>");
            stringBuilder.Append($"性别:{genderText}<br>");
            stringBuilder.Append($"  QQ:{userRow["qq"]}<br>");
            stringBuilder.Append($"    邮箱：{userRow["email"]}");
            stringBuilder.Append("  </p>");
            stringBuilder.Append($" <p>天气：{wea}  最高温度:{tem1}℃ 最低温度:{tem2}℃ </p>");
            stringBuilder.Append("</div>");
            stringBuilder.Append("</div>");
            return stringBuilder.ToString();
        }
        
        #endregion

        #region 日志加载
        public void InitNote()
        {
            DataSet ds = DbHelper.Query("select n.*,u.account from dbo.notes n inner join users u on u.id=n.user_id");
            rptNote.DataSource = ds;
            rptNote.DataBind();
        }
        #endregion

        protected void rptNote_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            #region 删除权限
            //获取当前行的发布人
            int userId = Convert.ToInt32((e.Item.FindControl("hfUserId") as HiddenField).Value);
            DataRow loginUser = (DataRow)Session["User"];
            //获取当前登录人权限
            int loginUserManager = Convert.ToInt32(loginUser["manager"]);
            int loginUserId = Convert.ToInt32(loginUser["id"]);
            //判断登录人是不是日志发布人或者管理员
            //是:不处理
            //不是:删除隐藏
            if (loginUserManager != 1 && loginUserId != userId)
            {
                e.Item.FindControl("LinkButton1").Visible = false;
                e.Item.FindControl("cbxItem").Visible = false;
            }
            #endregion
            

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            #region 全选删除
            int sign = 0;
            //遍历所有的数据行
            for (int i = 0; i < rptNote.Items.Count; i++)
            {
                //获取每一行的勾选框
                CheckBox cbx = rptNote.Items[i].FindControl("cbxItem") as CheckBox;
                int noteId = Convert.ToInt32((rptNote.Items[i].FindControl("hfNoteId") as HiddenField).Value);
                //判断勾选框是否勾选
                if (cbx.Checked == true)
                {
                    int flag = DbHelper.ExecuteSql("delete from notes where id=" + noteId);
                    if (flag > 0)
                    {
                        sign++;
                    }
                }
            }
            if (sign > 0)
                Response.Write($"<script>alert('删除成功，共删除{sign}条')</script>");
            InitNote();

            #endregion
        }

        protected void rptNote_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            #region  删除
            int id = Convert.ToInt32((e.Item.FindControl("hfNoteId") as HiddenField).Value);
            if (e.CommandName == "Delete")
            {
                int flag = DbHelper.ExecuteSql("delete from notes where id=" + id);
                if (flag > 0)
                {
                    Response.Write("<script>alert('删除成功')</script>");
                    InitNote();
                }
            }
            #endregion
        }
    }
    
}